package com.bfsuol.bfsuolframework.core.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet(value = "",loadOnStartup = 9)
public class SpringBeanLoader extends HttpServlet  {
   
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(SpringBeanLoader.class);
	private static WebApplicationContext ctx = null;
 
    public void init() throws ServletException{
    	log.info("SpringBeanLoader initialized!");
    	ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    /*static {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        ServletContext servletContext = attributes.getRequest().getServletContext();
        if (servletContext != null) {
            ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        } else {
            // 处理servletContext为null的情况
            // 可能需要记录日志或抛出一个更具体的异常
            throw new IllegalStateException("ServletContext is null.");
        }
    }*/
    
    protected static WebApplicationContext getWebApplicationContext(){
    	return ctx;
    }
    /**
     * 根据提供的bean名称得到相应的类     
     */
     public static Object getBean(String name) {
         return ctx.getBean(name);
     }
  
     /**
     * 根据提供的bean名称得到对应于指定类型的类
     * @param clazz 返回的bean类型,若类型不匹配,将抛出异常
     */
     @SuppressWarnings("unchecked")
     public static <T> T getBean(String name, T clazz) {
         return (T)ctx.getBean(name, clazz.getClass());
     }
     
     public static <T> T getBean(String name, Class<T> clazz) {
         return ctx.getBean(name, clazz);
     }

}